<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Log;
use think\Cache;
use think\Db;
use app\common\library\Upload;


/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $payConfig = ['alipay'=>['cid'=>'9338','cnum'=>'2088422402411613'],'wxpay'=>['cid'=>'9339','cnum'=>'1719940684']];
    protected $pid = '2025061614040962';
    protected $pkey = '4MZJ4aruah61UJNJCdz0Ue80tJzRCjr8';
    

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
    
    function getMillisecond() {
        list($usec, $sec) = explode(" ", microtime());  
        return round($usec*1000);
    }
    
    function getBaseUrl() {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $domain   = $_SERVER['HTTP_HOST']; 
        return  $protocol . "://" . $domain;
    }
    
    /**
     * 计算
     **/
    function get_sign(array $datas,$hashkey){
        ksort($datas);
        reset($datas);
         
        $pre =array();
        foreach ($datas as $key => $data){
            if(is_null($data)||$data===''){continue;}
            if($key=='sign' || $key=='sign_type'){
                continue;
            }
            $pre[$key]=stripslashes($data);
        }
         
        $arg  = '';
        $qty = count($pre);
        $index=0;
         
        foreach ($pre as $key=>$val){
            $arg.="$key=$val";
            if($index++<($qty-1)){
                $arg.="&";
            }
        }
        return strtolower(md5($arg.$hashkey));
    }
    
    /**
     *发起支付 
     **/
    public function postPayData()
    {
        $data = $this->request->param();
        Log::info('发起'.json_encode($data));
        if(empty($data['id'])){
            $this->error('id不能为空');
        }
        $out_trade_no = $data['id'];
        $order = Db::name('map_order')->where(['out_trade_no'=>$out_trade_no])->find();
        if(!$order){
            $this->error('id异常');
        }
        if(isset($order['pay_status'])){
            $this->error('支付状态异常');
        }
        if(empty($data['map_id'])){
            $this->error('id不能为空');
        }
        $map = Db::name('map_info')->where(['id'=>$data['map_id']])->find();
        if(!$map){
            $this->error('id异常.');
        }
        if(empty($data['type']) || !in_array($data['type'],['alipay','wxpay'])){
            $this->error('支付方式异常');
        }
        
        $type = $data['type'];//支持设置支付宝：alipay 微信支付：wxpay
        $notify_url = $this->getBaseUrl()."/api/index/notify";//异步回调地址
        $return_url = $this->getBaseUrl();//跳转地址
        $name = $map['name'];//商品名称
        $money = $map['money'];//订单金额，最多保留2位小数
        $sign_type = "MD5";//签名方式，目前仅支持MD5
        $param = $map['name'];//附加信息，回调时原样返回
        
        $arr = array(
            "pid" => $this->pid,
            "type" => $type,
            "notify_url" => $notify_url,
            "return_url" => $return_url,
            "out_trade_no" => $out_trade_no,
            "name" => $name,
            "money" => $money,
            "param" => $param,
            "sign_type" => $sign_type
        );
        $pid = $this->pid;
        $sign = $this->get_sign($arr,$this->pkey);
        $apiurl = 'https://zpayz.cn/';
        if($sign){
            
            $res = Db::name('map_order')->where(['id'=>$order['id']])->update(['map_id'=>$map['id']]);
            if(!$res){
                $this->error('程序异常,请稍后重试');
            }
        }
        $this->success('请求成功',['jumpUrl'=>$apiurl."submit.php?pid=$pid&type=$type&notify_url=$notify_url&return_url=$return_url&out_trade_no=$out_trade_no&name=$name&money=$money&param=$param&sign_type=$sign_type&sign=$sign"]);
       
        
        
    }
    
    /**
     *支付回调 
     **/
    public function notify()
    {
        $data = $this->request->param();
        //Log::info('支付回调'.json_encode($data));
        // print_r($data);die;
        $money = $data["money"]??'';
        $name = $data["name"]??'';
        $pid = $data["pid"]??'';
        $out_trade_no = $data["out_trade_no"]??'';
        $trade_no = $data["trade_no"]??'';
        $trade_status = $data["trade_status"]??'';
        $type = $data["type"]??'';
        $param = $data["param"]??'';
        $trade_status = $data["trade_status"]??'';
        $sign = $data["sign"]??'';
        $sign_type = $data["sign_type"]??'';
        
        $arr = array(
        	"pid" => $pid,
        	"type" => $type,
        	"out_trade_no" => $out_trade_no,
        	"trade_no" => $trade_no,
        	"name" => $name,
        	"money"	=> $money,
        	"param"	=> $param,
        	"trade_status"	=> $trade_status,
        	"sign_type"	=> $sign_type
        );
        
        if($sign==$this->get_sign($arr,$this->pkey)){
        	echo "success"; //返回success说明通知成功，不要删除本行
        	$order = Db::name('map_order')->where(['out_trade_no'=>$out_trade_no])->find();
            if($order){
                $arr = array_merge($arr,['pay_status'=>1,'pay_time'=>time()]);
                $res = Db::name('map_order')->where(['id'=>$order['id']])->update($arr);
                
            }
        }else{
        	echo "error";
        }
        
        
    }
    
    
    /**
     *店铺信息上传 
     **/
    public function postFormData()
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: Authorization, Content-Type, Token");
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
        
        $data = $this->request->param();
        Log::info(json_encode($data));
        if(empty($data['shop_name'])){
            $this->error('店铺名称不能为空');
        }
        $out_trade_no = date("YmdHis").$this->getMillisecond().mt_rand(100000,999999).mt_rand(100000,999999);
        $addData = ['shop_name'=>$data['shop_name'],'out_trade_no'=>$out_trade_no,'createtime'=>time()];
        if(!empty($data['shop_address'])){
            $addData['shop_address'] = $data['shop_address'];
        }
        if(!empty($data['connect_name'])){
            $addData['connect_name'] = $data['connect_name'];
        }
        if(!empty($data['connect_phone'])){
            $addData['connect_phone'] = $data['connect_phone'];
        }
       
        $res = Db::name('map_order')->insert($addData);
        if($res){
            $this->success('请求成功',['id'=>$out_trade_no]);
        }else{
            $this->error('请求失败,请稍后重试');
        }
        
        
        
    }
    
  
    public function getDyEcpm($game_id=0,$appid='',$secret='',$uuid='',$time=''){
        if(!$game_id || !$appid || !$secret){
            Log::info('参数缺失');
            // return '';
        }
        $token = $this->getDyToken($game_id,$appid,$secret);
        if(!$token){
            Log::info('token缓存'.$game_id);
            // $this->error('token异常,请稍后重试');
        }else{
            //接口查询只能按天  postman查询可以按小时
            if(!$time){
                $time = date('Y-m-d');
            }
            $page_no = Cache::get($time.'_'.$game_id.'_page_no',1);
            $page_size = 500;
            $url = "https://minigame.zijieapi.com/mgplatform/api/apps/data/get_ecpm?open_id=&mp_id=$appid&date_hour=$time&access_token=$token&page_no=$page_no&page_size=$page_size";
            $res = curlGet($url);
            
            if(!empty($res['data']['records']) && !empty($res['data']['total'])){
                $list = $res['data']['records'];
                $count = $res['data']['total'];
                $addData = [];
                $gameRatio = Db::name('game')->where('id',$game_id)->value('ratio');
                $dyIdList = Db::name('ad_record')->where('game_id',$game_id)->where('date',$time)->column('id','dy_id');
                // print_r($dyIdList);die;
                foreach ($list as $v) {
                    if(isset($dyIdList[$v['id']])){
                        continue;
                    }
                    $cost = !empty($v['cost'])?$v['cost']/100000:0;
                    $last_cost = 0;
                    if($cost && $gameRatio){
                        $integerPart = floor($cost); // 整数部分
                        $decimalPart = $cost - $integerPart; // 小数部分
                        $newIntegerPart = round($integerPart * $gameRatio / 100);
                        // 组合新数字（整数部分 + 原始小数部分）
                        $last_cost = $newIntegerPart + $decimalPart;
                    }
                    $addData = ['date'=>$time,'aid'=>$v['aid'],'dy_id'=>$v['id'],'open_id'=>$v['open_id'],'cost'=>$cost,'event_name'=>$v['event_name'],'event_time'=>$v['event_time'],'createtime'=>time(),'week'=>date("W"),'game_id'=>$game_id,'uuid'=>$uuid,'ratio'=>$gameRatio,'last_cost'=>$last_cost];
                    $recordId = Db::name('ad_record')->insertGetId($addData);
                    
                    if($recordId){
                        $updateData = [];
                        $week_count= Db::name('ad_record')->where('game_id',$game_id)->where('week',date("W"))->where('open_id',$v['open_id'])->count();
                        if($week_count){
                            $updateData['week_count'] = $week_count;
                            
                        }
                        $dy_user= Db::name('dy_user')->where('open_id',$v['open_id'])->field('game_name,douyin_name,terrace,image,brand')->find();
                        if($dy_user){
                            $updateData = array_merge($updateData,$dy_user);
                            
                        }
                        if($updateData){
                            Db::name('ad_record')->where('id',$recordId)->update($updateData);
                        }
                    }
                   
                }
                
                Log::info($time.'_'.$game_id.'_'.$page_no.'_'.$count.'数据获取成功');
                if($count > ($page_no * $page_size)){
                    $page_no += 1;
                    Cache::set($time.'_'.$game_id.'_page_no',$page_no,86400);
                    Log::info($time.'_'.$game_id.'_'.$page_no.'再次获取');
                    
                }
                Log::info($time.'请求成功'.$game_id.'_'.$page_no);
                // $this->success('请求成功');
            }else{
                Log::info($time.'暂无记录数据'.$game_id.'_'.$page_no);
                // $this->error('暂无记录数据,请稍后重试');
            }
        }
    }
    
    
    /**
     *地图信息获取 
     **/
    public function mapDataList(){
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        header('Access-Control-Allow-Credentials: true');
        $page = $this->request->param('page',1);
        $pageSize = $this->request->param('page_size',20);
        $list = Db('map_info')->limit(($page - 1)*$pageSize,$pageSize )
        ->field('id,name,money')->order('id', 'desc')
        ->select();

        $this->success('获取成功',['count'=>count($list),'list'=>$list]);
    }
    
    /**
     *支付成功订单信息获取 
     **/
    public function orderDataList(){
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        header('Access-Control-Allow-Credentials: true');
        $page = $this->request->param('page',1);
        $pageSize = $this->request->param('page_size',20);
        $list = Db('map_order')->where('pay_status',1)->limit(($page - 1)*$pageSize,$pageSize )
        ->field('connect_phone as phone,pay_time')->order('pay_time', 'desc')
        ->select();
        foreach ($list as &$v){
            $v['pay_time'] = date('Y-m-d',$v['time']);
        }
        $this->success('获取成功',['count'=>count($list),'list'=>$list]);
    }
    
    public function loginQuery(){
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        header('Access-Control-Allow-Credentials: true');
        $username = $this->request->param('username','');
        $password = $this->request->param('password','');
        if(!$username || !$password){
            $this->error('账号密码不能为空');
        }
        $gameInfo = Db('game')->where(['username'=>$username])->find();
        if(!$gameInfo){
            $this->error('账号不存在');
        }
        if($gameInfo['password'] != getEncryptPassword($password, $gameInfo['uuid'])){
            $this->error('账号密码不匹配');
        }
        $this->success('登陆成功',['name'=>$gameInfo['name'],'uuid'=>$gameInfo['uuid']]);
    }
    
    
    
}
